package com.meitianhui.convenitenbuy.module.mine.presenter;

import android.content.DialogInterface;
import android.util.Pair;

import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.model.EaseAtMessageHelper;
import com.meitianhui.convenitenbuy.hyphenate.db.InviteMessgeDao;
import com.meitianhui.convenitenbuy.module.mine.contract.MessageDispitchContract;
import com.meitianhui.convenitenbuy.module.mine.ui.activity.MessageDisPitchActivity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * Created by amy on 2017/11/22.
 */

public class MessageDispitchPresenter implements MessageDispitchContract.Presenter {

    private MessageDispitchContract.View mView;
    private MessageDisPitchActivity mContext;

    public MessageDispitchPresenter(MessageDisPitchActivity activity,
                                    MessageDisPitchActivity context) {
        this.mView = activity;
        this.mContext = context;
    }

    @Override
    public void attachView(Object view) {
    }

    @Override
    public void detachView() {
    }

    @Override
    public List<EMConversation> getConversationList() {
        // get all conversations
        Map<String, EMConversation> conversations =
                EMClient.getInstance().chatManager().getAllConversations();
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        /*
         * lastMsgTime will change if there is new message during sorting
         * so use synchronized to make sure timestamp of last message won't change.
         */
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    if (conversation.getType() != EMConversation.EMConversationType.ChatRoom) {
                        sortList.add(new Pair<Long, EMConversation>(
                                conversation.getLastMessage().getMsgTime(), conversation));
                    }
                }
            }
        }

        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }

        return list;
    }

    /**
     * 添加消息监听
     */
    @Override
    public void addMessageListener() {
        EMClient.getInstance().chatManager().addMessageListener(new EMMessageListener() {
            @Override
            public void onMessageReceived(List<EMMessage> list) {
                // 获取最新消息
                mView.refreshConversation();
            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> list) {
            }

            @Override
            public void onMessageRead(List<EMMessage> list) {
            }

            @Override
            public void onMessageDelivered(List<EMMessage> list) {
            }

            @Override
            public void onMessageRecalled(List<EMMessage> list) {
            }

            @Override
            public void onMessageChanged(EMMessage emMessage, Object o) {
            }
        });
    }

    @Override
    public void remove(List<EMConversation> conversationList, int position, int which,
                       DialogInterface dialog) {
        EMConversation tobeDeleteCons = conversationList.get(position);
        if (tobeDeleteCons == null) {
            mView.dismissDialog(dialog);
            return;
        }

        if (tobeDeleteCons.getType() == EMConversation.EMConversationType.GroupChat) {
            EaseAtMessageHelper.get().removeAtMeGroup(tobeDeleteCons.conversationId());
        }

        if (which == 1) {
            try {
                // delete conversation
                EMClient.getInstance().chatManager().deleteConversation(tobeDeleteCons.conversationId(), true);
                InviteMessgeDao inviteMessgeDao = new InviteMessgeDao(mContext);
                inviteMessgeDao.deleteMessage(tobeDeleteCons.conversationId());
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (which == 0) {
            try {
                // delete conversation
                EMClient.getInstance().chatManager().deleteConversation(tobeDeleteCons.conversationId(), false);
                InviteMessgeDao inviteMessgeDao = new InviteMessgeDao(mContext);
                inviteMessgeDao.deleteMessage(tobeDeleteCons.conversationId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * sort conversations according time stamp of last message
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {
                if (con1.first == con2.first) {
                    return 0;
                } else if (con2.first > con1.first) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });
    }

}
